package cn.edu.seu.herald.informationplatform.dao.database;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import cn.edu.seu.herald.informationplatform.bean.league.Album;

import com.mysql.jdbc.Statement;

public class AttentionDao extends DataAccessObject{
	private static AttentionDao daoInstance=null;
	protected AttentionDao(){
		
	}
	
	public static AttentionDao getDao(){
		if(daoInstance==null){
			daoInstance=new AttentionDao();
		}
		return daoInstance;
	}
	
	//judge have id
	public boolean hasId(int id) throws SQLException{
		Connection con=getConnectionLeague();
		try {
			PreparedStatement ps = con.prepareStatement("Select * from lg_league_attention where id=?");
			ps.setInt(1,id);
			ResultSet rs = ps.executeQuery();
			int i = 0;
			while(rs.next()){
			i = rs.getRow();
			}
			closeRs(rs);
			if(i>0){
			return true;
			}else {
				return false;
			}
		} catch (SQLException e) {
			e.printStackTrace();
			throw e;
		}
		finally{
			closeCon(con);
		}
	}
	
	//judge have id
	public boolean contains(int league_id,int user_id) throws SQLException{
		Connection con=getConnectionLeague();
    	try{
    		PreparedStatement ps=con.prepareStatement("SELECT COUNT(*) FROM lg_league_attention WHERE league_id=? AND user_id=? LIMIT 1");
    		ps.setInt(1, league_id);
    		ps.setInt(2, user_id);
    		ResultSet rs= ps.executeQuery();
    		if (!rs.next()) {
    			throw new RuntimeException();
    		}
    		
    		int number = rs.getInt(1);
    		return number > 0;
    	} finally {
    		con.close();
    	}
    	
	}
	
	public int addAttention(int league_id,int user_id) throws SQLException{
		Connection con=getConnectionLeague();
    	try{
    	PreparedStatement ps=con.prepareStatement("insert into lg_league_attention(league_id,user_id) values (?,?)",Statement.RETURN_GENERATED_KEYS);
    	ps.setInt(1,league_id);
    	ps.setInt(2, user_id);
    	ps.executeUpdate();
    	ResultSet rsResultSet=ps.getGeneratedKeys();
		int new_id=-1;
		if(rsResultSet.next()){
			new_id=rsResultSet.getInt(1);
		}
		closeRs(rsResultSet);
		return new_id;
    	}catch (SQLException e) {
		e.printStackTrace();
		throw e;
	}
	finally{
		closeCon(con);
	}
	}
	
	//delete
	public void deleteAttention(int league_id,int user_id) throws SQLException{
		Connection con=getConnectionLeague();
    	try{
    	PreparedStatement ps=con.prepareStatement("delete from lg_league_attention where league_id=? and user_id=?");
    	ps.setInt(1,league_id);
    	ps.setInt(2, user_id);
    	ps.executeUpdate();
    	}catch (SQLException e) {
		e.printStackTrace();
		throw e;
	}
	finally{
		closeCon(con);
	}
	}
	
	
}
